import './App.css';
import {useEffect,useState,useCallback,useRef,memo, useReducer} from 'react';
import {createAdd,createSet,createRemove,createToggle} from './actions';
import reducer from './reducers';
const LS_KEY = 'asdifj';



function bindActionCreators(actionCreators,dispatch) {
    const ret = {};
    for(let key in actionCreators) {
        ret[key] = function(...args) {
            const actionCreator = actionCreators[key];
            const action = actionCreator(...args);
            dispatch(action);
        }
    }
    return ret;
}

const Control = memo(function Control(props) {
    const {addTodo} = props;
    const inputRef = useRef()
    const onSubmit=(e)=>{
        e.preventDefault();
        const newText = inputRef.current.value.trim();
        if(newText==='') {return }
        addTodo({
            id:Date.now(),
            text:newText,
            complete:false
        });

        inputRef.current.value = '';
    }
    return (
        <div className='control'>
            <h1>todos</h1>
            <form onSubmit={onSubmit}>
                <input type="text"
                ref={inputRef}
                className="new-todo" 
                placeholder="What needs to be done?"/>
            </form>
        </div>
    )
});

const TodItem = memo(function TodItem(props){
    const {
        todo:{
            id,text,complete
        },
        removeTodo,
        toggleTodo
    } = props;

    const onChange = ()=>{
        toggleTodo(id);
    };

    const onRemove = ()=>{
        removeTodo(id);
    };

    return (
        <li className={complete?'checked':''}>
            
            <label><input type="checkbox" onChange={onChange} checked={complete} />{text}</label>
            <button onClick={onRemove}>&#xd7;</button>
        </li>
    )
});

const Todos = memo(function Todos(props) {
    const {todos, removeTodo,toggleTodo} = props;
    return (
        <ul className="todo-list">
            {
                todos.map(todo=>{
                    return (
                        <TodItem key={todo.id} todo={todo} removeTodo={removeTodo} toggleTodo={toggleTodo} />
                    )
                })
            }
        </ul>
    )
})


function App() {
    const [todos, setTodos] = useState([]);
    const [incrementCount, setIncrementCount] = useState(0);

    
    const dispatch = useCallback((action)=>{
        const state = {
            todos,
            incrementCount,
        };

        const setters = {
            todos:setTodos,
            incrementCount:setIncrementCount
        };

        const  newState = reducer(state,action);
        for (let key in newState) {
            setters[key](newState[key]);
        }

        


    },[todos,incrementCount]);

    useEffect(()=>{
        const todos = localStorage.getItem(LS_KEY)?JSON.parse(localStorage.getItem(LS_KEY)):[];
        dispatch(createSet(todos));
    },[])

    useEffect(()=>{
        localStorage.setItem(LS_KEY,JSON.stringify(todos))
    },[todos])

    return (
        <div className="App">
            <Control 
            {...bindActionCreators({
                addTodo:createAdd
            },dispatch)}
            />
            <Todos 
            {...bindActionCreators({
                removeTodo:createRemove,
                toggleTodo:createToggle
            },dispatch)}
              todos={todos} />
        </div>
    );
}

export default App;
